#!/usr/bin/python2
# -*- coding: utf8 -*-
from PyQt4 import QtCore, QtGui, Qt, QtDeclarative
from models.JobsModel import JobsModel
from utils.log import log
from models.BaseTimeModel import BaseTimeModel

class MonthJobModel(BaseTimeModel):
    DAY_ROLE = 0
    JOBS_ROLE = 1
    MONTH_ROLE = 2
    WEEK_DAY_ROLE = 3
    SECONDS_ROLE = 4

    limitJobsInElement = 5

    _fromDate = QtCore.QDate.currentDate()
    dateChange = QtCore.pyqtSignal()

    def __init__(self, db, fromDate=QtCore.QDate.currentDate(), parent=None):
        self._fromDate = fromDate
        BaseTimeModel.__init__(self, fromDate, parent)
        self._db = db
        self.setRoleNames({self.DAY_ROLE: 'day', self.MONTH_ROLE: 'month', self.JOBS_ROLE: 'jobsModel', self.WEEK_DAY_ROLE: 'dayOfWeek', self.SECONDS_ROLE: 'dateInSeconds'})

    def data(self, index, role):
        if not index.isValid: return QtCore.QVariant()
        dayOfWeek = self._fromDate.dayOfWeek()
        row = index.row() - dayOfWeek + 1

        if role == self.DAY_ROLE:
            day = self._fromDate.addDays(row)
            return QtCore.QVariant(day.day())
        if role == self.MONTH_ROLE:
            day = self._fromDate.addDays(row)
            return QtCore.QVariant(day.month())
        if role == self.WEEK_DAY_ROLE:
            day = self._fromDate.addDays(row)
            return QtCore.QVariant(day.dayOfWeek())
        if role == self.JOBS_ROLE:
            fromDate = self._fromDate.addDays(row)
            fromTime = QtCore.QDateTime(fromDate).toTime_t()
            toDate = fromDate.addDays(1)
            toTime = QtCore.QDateTime(toDate).toTime_t()
            jobsModel = JobsModel(self._db, fromTime, toTime, self.limitJobsInElement, self)
            return QtCore.QVariant(jobsModel)
        if role == self.SECONDS_ROLE:
            fromDate = self._fromDate.addDays(row)
            fromTime = QtCore.QDateTime(fromDate).toTime_t()
            return fromTime
        return QtCore.QVariant()

    def rowCount(self, parent=QtCore.QModelIndex()):
        dayOfWeek = self._fromDate.dayOfWeek()
        commonCount = dayOfWeek - 1 + self._fromDate.daysInMonth()
        return commonCount

    def getMonth(self):
        return self._fromDate.month()

    month = QtCore.pyqtProperty("int", fget=getMonth, notify=dateChange)
